package cryptography

import (
	"encoding/base64"
	"errors"
	"strings"
)

func ParseBasicAuth(auth string) (username, password string, resErr error) {
	basicPrefix := "Basic "
	// 检查是否以 "Basic " 开头
	if !strings.HasPrefix(auth, basicPrefix) {
		resErr = errors.New("authorization header is not Basic")
		return
	}

	// 提取 Base64 编码部分
	encodedCredentials := strings.TrimPrefix(auth, basicPrefix)

	// 解码 Base64
	decodedBytes, err := base64.StdEncoding.DecodeString(encodedCredentials)
	if err != nil {
		resErr = err
		return
	}

	// 转换为字符串并分割为用户名和密码
	credentials := string(decodedBytes)
	parts := strings.SplitN(credentials, ":", 2) // 限制分割为两部分
	if len(parts) != 2 {
		resErr = errors.New("invalid credentials format")
		return
	}

	username = parts[0]
	password = parts[1]
	return
}
